const {ParamVerifyTypeError, ParamVerifyMissError} = require("../commonError/ParamError");
const {isDef} = require("../utils/utils");
module.exports.customValidateParams = function (params, cb) {
    return cb(params)
}
/**
 * ValidateParams
 * @description 校验接口接收的参数。有参数则先校验是否必传，无论是否必传，都校验类型。无参数直接赋值默认值
 * @param  {object} reqParams 接口参数
 * @param  {object} readRulers 读取规则
 * @return {Promise<object>}
 */
//[
// 字段名1：{ type: 'array', default:'', required: true }
// 字段名2：{ type: 'array', default:'', required: true }
// ]
module.exports.validateParams = function (reqParams, readRulers, callback = null) {
    return new Promise((resolve, reject) => {
        let reqDealRes = {}
        for (let rulerItemKey in readRulers) {
            if (readRulers[rulerItemKey]['required'] === true) {//必填字段
                if (!isDef(reqParams[rulerItemKey])) {
                    reject(new ParamVerifyMissError(rulerItemKey))
                    return
                }
                //校验类型
                verifyType(reqParams,readRulers,rulerItemKey)

                reqDealRes[rulerItemKey] = reqParams[rulerItemKey]
            } else {//非必填字段
                if (!isDef(reqParams[rulerItemKey])) {//非必填字段不存在，采用默认值
                    reqDealRes[rulerItemKey] = readRulers[rulerItemKey]['default']

                } else {//非必填字段存在，则继续校验类型
                    //校验类型
                    verifyType(reqParams,readRulers,rulerItemKey)
                    reqDealRes[rulerItemKey] = reqParams[rulerItemKey]

                }
            }
        }
        if (callback instanceof Function) {
            try {
                let callbackResData = callback(reqDealRes)
                resolve(callbackResData)
            } catch (err) {
                reject(err)
            }
            return;
        }
        resolve(reqDealRes)
    })


}

function verifyType(reqParams,readRulers,rulerItemKey) {
    if (!isDef(readRulers[rulerItemKey]['type'])) {
        console.error("必传参数，必须指定类型type")
        return
    }
    if (readRulers[rulerItemKey]['type'] !== typeof reqParams[rulerItemKey]) {
        throw new ParamVerifyTypeError(rulerItemKey)
        return
    }
    if (isDef(readRulers[rulerItemKey]['strReg']) && !readRulers[rulerItemKey]['strReg'].test(reqParams[rulerItemKey])) {
        throw new ParamVerifyTypeError(rulerItemKey)
        return
    }
}


